<?php
/**
 * RedXenon Framework
 * 
 * LICENSE
 * 
 * This source file is subject to the New BSD license that is bundled
 * with this package in the file LICENSE.txt
 * A copy of this license can be found in the world-wide-web at this URL:
 * http://www.redxenon.com/license/new-bsd-license.txt
 * 
 * RedXenon LogManager (RXLogManager.php)
 * Class to manage log files across the different possible usages
 * 
 * @category RedXenon
 * @package RedXenon_Log
 * @copyright Copyright (c) 2011 Red Xenon (http://www.redxenon.com)
 * @version $Id: RXLogManager.php 1.0 2011-04-22 $ 
 */
class RXLogManager {
	
	/**
	 * @var resource
	 */
	var $logHandler;
	
	/**
	 * @var String
	 */
	var $filePath;
	
	/*
	 * @var Integer
	 */
	var $maxFileSize;
	
	/**
	 * Opens a logFile
	 */
	public function open(){
		if(file_exists($this->filePath)){
			
			$mode = "a";
			
			if($this->maxFileSize > 0){
				/* The backup process is enabled */
				clearstatcache();
				if(filesize($this->filePath) > $this->maxFileSize){
					
					/* Backup directory creation based in date and file name */
					$backupDirectory = dirname($this->filePath)."/HISTORICAL_".strtoupper(str_replace(".", "", basename($this->filePath)))."/".date("Y")."/".date("m")."/";				
					if(!is_dir($backupDirectory))
						mkdir($backupDirectory, 0777, TRUE);
											
					file_put_contents(	$backupDirectory.date("Ymd")."_".str_replace(".", "", basename($this->filePath)), 
														file_get_contents($this->filePath), 
														FILE_APPEND | LOCK_EX);
					$mode = "w";
				}
			}
			
			$this->logHandler = @fopen($this->filePath, $mode);
			
		}else{
			$this->logHandler = @fopen($this->filePath, "w");
		}
		
		if($this->logHandler){
			flock($this->logHandler, LOCK_EX);
		}else{		
			throw new Exception("Could not open log file @ ".$this->filePath);
		}
	}
	
	/**
	 * Closes the log file handler
	 */
	public function close(){
		flock($this->logHandler, LOCK_UN);
		fclose($this->logHandler);
		unset($this->logHandler);
	}
	
	/**
	 * Writes a message in a log file
	 * @param String $message
	 * @param Integer $priority
	 * @param String $file
	 * @param Integer $line
	 */
	public function write($message, $file = null, $line = null){
		throw new Exception("Function to be implemented in child classes");
	}
}

?>